<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- crossorigin="anonymous" 即向源发送请求时不携带cookie -->
    <link
      crossorigin="anonymous"
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
  </head>
  <body>
    <div class="container">
      <h2>jQuery发送Ajax请求</h2>
      <button class="btn btn-primary">Get请求</button>
      <button class="btn btn-danger">Post请求</button>
      <button class="btn btn-info">通用型方法ajax</button>
    </div>
  </body>

  <script>
    // $.get(url,params,callback,responseType)
    //eg:$.get("",{a:1,b:2},function(){},"json")

    $("button")
      .eq(0)
      .click(function () {
        $.get(
          "http://127.0.0.1:9000/server",
          { a: 10, b: 20 },
          function (data) {
            console.log(data);
          }
        );
      });

    $("button")
      .eq(1)
      .click(function () {
        $.post(
          "http://127.0.0.1:9000/server",
          { a: 10, b: 20 },
          function (data) {
            //let obj = JSON.parse(data);  //不传递responseType 则data为字符串，需要JSON.parse
            console.log(data.name); //传递responseType, 则data为对象可以直接使用
          },
          "json"
        );
      });

    $("button")
      .eq(2)
      .click(function () {
        $.ajax({
          url: "http://127.0.0.1:9000/server2",
          data: { a: 10, b: 20 }, //参数
          type: "post", //请求类型
          dataType: "json", //响应体结果 返回data为对象可以直接使用
          success: function (data) {
            //成功回调
            console.log(data.name);
          },
          timeout: 2000, //设置超时时间
          error: function () {
            console.log("出错啦");
          }, //失败回调
          headers: { c: 200, d: 300 }, //设置请求头
        });
      });
  </script>
</html>
